<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use DB;
class LoginController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Login Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles authenticating users for the application and
    | redirecting them to your home screen. The controller uses a trait
    | to conveniently provide its functionality to your applications.
    |
    */

    use AuthenticatesUsers;

    /**
     * Where to redirect users after login.
     *
     * @var string
     */
    protected $redirectTo = '/home';

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('guest')->except('logout');
    }

    /**
     * @abstract 重构login方法
     * @param Request $request
     */
    public function login(Request $request)
    {
        $arrPostData = $request->all();
        $arrUser = DB::select('select * from users where email = ? and password = ?',[$arrPostData['email'],md5($arrPostData['password'])]);
        if(is_array($arrUser) && count($arrUser) > 0){
            $objUser = array_shift($arrUser);
            $_SESSION['userinfo'] = $objUser;
            $request->session()->push('userinfo',$objUser);
            return response()->json(['code' => 0,'message' => 'login success'], 200);
        }else{
            return response()->json(['code' => 1,'message' => 'login failed'], 200);
        }
    }

    /**
     * @abstract 用户的退出响应函数
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function logout(Request $request)
    {
        $request->session()->forget('userinfo');
        return response()->json(['code' => 0,'message' => 'logged out'], 200);
    }


    /**
     * @abstract 通过微信小程序对照的
     */
    public function getWxUserInfo(){
        $appId = 'wx3a72fa527e7c1088';
        $secretId = 'dd0ee595380b124de0a1b2dc5da537f1';
        $url = 'https://api.weixin.qq.com/sns/jscode2session?appid='.$appId.'&secret='.$secretId.'&grant_type=authorization_code&js_code='.$_GET['code'];
        $result = file_get_contents($url);
        return response()->json(['code' => 0,'message' => 'userinfo', 'data' => $result], 200);
    }
}
